# 作者: 肖老师
# 2024年12月19日02时49分46秒
# xxxrlmk@163.com
# 介绍sorted与sort区别
list1 = [1, 3, 2, 4, 5, 3, 2]
print(sorted(list1))
print(list1)

a = [5, 2, 3, 1, 4]
a.sort()
print(a)

str_list = "This is a test string from Andrew".split()
print(sorted(str_list, key=str.lower))

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 13),
]


def compare_rule(element):
    return element[2]  # sorted拿哪一个数据去比较,比较的关键字


print(sorted(student_tuples, key=compare_rule))  # 给key传递的函数叫回调函数（等一会儿才调用的函数）


# 排自定义对象
class Student:

    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __repr__(self):
        return repr((self.name, self.grade, self.age))  # 跟__str__内置方法一样，只是更高级，能返回更多类型数据，而不只是字符串


s = Student('john', 'A', 15)
print(s)

student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
print('-' * 50)


def compare_object(s):
    return s.age


print(sorted(student_objects, key=compare_object))
print('-' * 50)
# lambda就是匿名函数,可阅读性好
print(sorted(student_objects, key=lambda s: s.age))

from operator import itemgetter, attrgetter

print(sorted(student_tuples, key=itemgetter(2)))

print(sorted(student_objects, key=attrgetter('age')))

# 多层排序
print('-' * 50+'多层排序')
print(sorted(student_tuples, key=itemgetter(1, 2), reverse=True))

print(sorted(student_objects, key=attrgetter('grade', 'age')))
